package com.jrx.anytxn.transaction.job.autoPayment.step;

import com.jrx.anytxn.customer.dto.customer.CustomerRes;
import com.jrx.anytxn.customer.entity.CmCustomerBankcardInfo;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerBankcardInfoMapper;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.PrProductTable;
import com.jrx.anytxn.param.service.product.IProductTableService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.bean.DebtBean;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.AmLoanAccountInfo;
import com.jrx.anytxn.transaction.entity.BtAutoPaymentList;
import com.jrx.anytxn.transaction.entity.TlPaymentLog;
import com.jrx.anytxn.transaction.entity.TlPaymentMapping;
import com.jrx.anytxn.transaction.job.autoPayment.bean.PaymentLogBean;
import com.jrx.anytxn.transaction.mapper.ext.ExtAmLoanAccountInfoMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlPaymentLogMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlPaymentMappingMapper;
import com.jrx.anytxn.transaction.service.IPaymentLogService;
import com.jrx.anytxn.transaction.service.impl.DebtCalculationServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 按客户级扣款批扣准备processor
 *
 * @author : zhenghaopu
 * 2019/11/22
 */
@Service
public class AutoPaymentPreLoanProcessor implements ItemProcessor<BtAutoPaymentList, PaymentLogBean> {

    private Logger logger = LoggerFactory.getLogger(AutoPaymentPreLoanProcessor.class);

    @Autowired
    private IOrganizationTableService organizationTableService;

    @Autowired
    private ExtCmCustomerBankcardInfoMapper extCmCustomerBankcardInfoMapper;

    @Autowired
    private ExtAmLoanAccountInfoMapper extAmLoanAccountInfoMapper;

    @Autowired
    private ExtTlPaymentLogMapper extTlPaymentLogMapper;

    @Autowired
    private ExtTlPaymentMappingMapper extTlPaymentMappingMapper;

    @Autowired
    private DebtCalculationServiceImpl debtCalculationService;

    @Autowired
    private IPaymentLogService paymentLogService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private IProductTableService productTableService;


    @Override
    public PaymentLogBean process(BtAutoPaymentList item) throws Exception {
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        Date businessDate = org.getNextProcessingDate();

        //查询客户是否有默认还款卡
        CmCustomerBankcardInfo condition = new CmCustomerBankcardInfo();
        condition.setCustomerId(item.getCustomerId());
        condition.setChannel(item.getChannel());
        condition.setDefaultPayFlag(TransBizConstant.Y_FLAG);
        List<CmCustomerBankcardInfo> bankcardInfoList = extCmCustomerBankcardInfoMapper.selectByCondition(condition);
        if(CollectionUtils.isEmpty(bankcardInfoList)){//不存在默认还款卡
            return  null;
        }

        List<String> statusList = Arrays.asList(TransBizConstant.LOAN_STATUS_1,TransBizConstant.LOAN_STATUS_2);
        //查询客户正常状态贷款账户列表
        List<AmLoanAccountInfo> accountInfos =
                extAmLoanAccountInfoMapper.selectByCustAndChannelAndStatus(item.getCustomerId(),item.getChannel(),
                        item.getTenantId(),statusList);
        //订单列表为空
        if(CollectionUtils.isEmpty(accountInfos)){
            return null;
        }

        //筛选符合条件的订单
        Predicate<AmLoanAccountInfo> getOnDue = loan -> TransBizConstant.LOAN_STATUS_1.equals(loan.getAccountStatus())
                && loan.getNextPaymentDate().compareTo(businessDate) == 0;
        Predicate<AmLoanAccountInfo> getOverDue = loan -> TransBizConstant.LOAN_STATUS_2.equals(loan.getAccountStatus());
        List<AmLoanAccountInfo> newLoanAcctList = accountInfos.stream()
                .filter(getOnDue.or(getOverDue)).collect(Collectors.toList());


        //查詢客戶下需要处理的还款流水
        List<String> sumStatusList = Arrays.asList(TransBizConstant.PAYMENT_LOG_SUM_STATUS_O,
                TransBizConstant.PAYMENT_LOG_SUM_STATUS_T, TransBizConstant.PAYMENT_LOG_SUM_STATUS_D);
        List<TlPaymentLog> tlPaymentLogList =
                extTlPaymentLogMapper.selectListBySumStatusForBatch(item.getCustomerId(),
                        item.getChannel(),sumStatusList);
        //还款流水不空 与订单匹配
        if(CollectionUtils.isNotEmpty(tlPaymentLogList)){
            List<String> seqNoList = tlPaymentLogList.stream().map(TlPaymentLog::getSeqNo).collect(Collectors.toList());
            //获取还款流水对应的订单信息
            List<String> loanIdList = extTlPaymentMappingMapper.selectBySeqNoListForBatch(seqNoList);
            //剔除正在还款中的数据
            newLoanAcctList.removeIf(amLoanAccountInfo -> loanIdList.contains(amLoanAccountInfo.getLoanId()));
        }
        //验证后的贷款列表不为空
        if(CollectionUtils.isEmpty(newLoanAcctList)){
            return  null;
        }

        //查询客户信息
        CustomerRes customer = customerService.getCustomerByChannelAndCustomerIdAndTensnId(item.getChannel(),
                item.getCustomerId(),item.getTenantId());

        //查询产品信息
        PrProductTable product =
                productTableService.findProByProIdAndOrgId(newLoanAcctList.get(0).getProductId(),
                        org.getOrganizationId(),item.getTenantId());

        //还款流水列表
        List<TlPaymentLog> savePaymentLogList = new ArrayList<>(newLoanAcctList.size());
        //还款流水与订单映射信息
        List<TlPaymentMapping> tlPaymentMappingList = new ArrayList<>(newLoanAcctList.size());

        //遍历订单计算欠款
        for (AmLoanAccountInfo amLoanAccountInfo : newLoanAcctList) {
            //计算欠款
            DebtBean debtBean = debtCalculationService.getBalance(amLoanAccountInfo,businessDate,null, true,true,
                    null);
            if(debtBean.getTotalAmount().compareTo(BigDecimal.ZERO)<1){
                continue;
            }
            //构建还款流水
            TlPaymentLog tlPaymentLog =
                    paymentLogService.buildTlPaymentLog(TransBizConstant.REPAYMENT_TYPE_AUTO,
                            bankcardInfoList.get(0), customer, debtBean.getTotalAmount(), businessDate, product, null);
            tlPaymentLog.setDescription(TransBizConstant.REPAYMENT_TYPE_AUTO_ORDER_NAME);//交易说明	　
            savePaymentLogList.add(tlPaymentLog);

            //构建还款流水与订单映射
            TlPaymentMapping tlPaymentMapping = paymentLogService.buildTlPaymentMapping(item.getCustomerId(),
                    tlPaymentLog.getSeqNo(),amLoanAccountInfo.getLoanId(),item.getTenantId());
            tlPaymentMappingList.add(tlPaymentMapping);

        }
        //判断是否有还款流水
        if(CollectionUtils.isNotEmpty(savePaymentLogList)){//有还款流水 返回信息
            //还款流水信息
            PaymentLogBean paymentLogBean = new PaymentLogBean();
            paymentLogBean.setTlPaymentLogList(savePaymentLogList);
            paymentLogBean.setTlPaymentMappingList(tlPaymentMappingList);
            return paymentLogBean;
        }
        return null;
    }
}
